//
//  MainViewController.m
//  PenTa
//
//  Created by iOS Three on 14/9/26.
//  Copyright (c) 2014年 iOS Three. All rights reserved.
//

#import "MainViewController.h"

#define FILEPATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1]];
    [self addViewsAndKits];
}

//初始化视图、控件、数据
-(void)addViewsAndKits {
    _headerImgView = [[UIImageView alloc] init];
    [_headerImgView setFrame:CGRectMake(0, 0, 320,182)];
    _headerImgView.image = [UIImage imageNamed:@"di_01"];
    _boole = YES;
    _headerImgView.userInteractionEnabled = YES;
    
    _voiceList = [[UITableView alloc] init];
    if (self.view.frame.size.height <500) {
        [_voiceList setFrame:CGRectMake(0, 182, 320, 294)];

    }else{
        [_voiceList setFrame:CGRectMake(0, 182, 320, 384)];

    }
    _voiceList.dataSource = self;
    _voiceList.delegate = self;
   // [_voiceList setEditing:YES animated:YES];
    [self.view addSubview:_voiceList];
    
    
    [self.view addSubview:_headerImgView];
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    _fileArray = [[NSMutableArray alloc] initWithArray:[fileManager contentsOfDirectoryAtPath:FILEPATH error:nil]];
    _timeArray = [[NSMutableArray alloc] init];
    _imagesArray = [[NSMutableArray alloc] init];
    if (_fileArray.count != 0) {
    for (int i = 0; i<_fileArray.count; i++) {
        if ([[_fileArray objectAtIndex:i] hasSuffix:@".caf"]) {
            [_timeArray addObject:[_fileArray objectAtIndex:i]];
        }else{
            [_imagesArray addObject:[_fileArray objectAtIndex:i]];
        }
    }
    }
    
    _addImgBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [_addImgBt setFrame:CGRectMake(245, 43, 45, 45)];
    [_addImgBt setBackgroundImage:[UIImage imageNamed:@"jia_03"] forState:UIControlStateNormal];
    [_addImgBt setTag:9999];
    [_addImgBt setBackgroundColor:[UIColor clearColor]];
    [_addImgBt addTarget:self action:@selector(Click:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_addImgBt];

    _deatilView =[[UIView alloc] init];
    if (self.view.frame.size.height < 500) {
        [_deatilView setFrame:CGRectMake(0, 0, 320, 480)];
    }else{
        [_deatilView setFrame:CGRectMake(0, 0, 320, 568)];
    }
    [_deatilView setBackgroundColor:[UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1]];
    [_deatilView setAlpha:1];
    
    
}


-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionDown) {
        if (_tapeBt != nil) {
            [_tapeBt removeFromSuperview];
        }
        
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 485.5, 320, 82.5)];
        imageview.image = [UIImage imageNamed:@"di_02"];
        [_headerImgView setFrame:CGRectMake(0, 0, 320, 568)];
        _headerImgView.image = [UIImage imageNamed:@""];
        _boole = NO;
        [self.view addSubview:imageview];
        _headerImgView.backgroundColor = [UIColor whiteColor];
        [_addImgBt setBackgroundImage:[UIImage imageNamed:@"photo"] forState:UIControlStateNormal];
        [_addImgBt setFrame:CGRectMake(95, 250, 130, 145)];
        _tapeBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_tapeBt setBackgroundImage:[UIImage imageNamed:@"mike_05"] forState:UIControlStateNormal];
        // Set record start action for UIControlEventTouchDown
        [_tapeBt addTarget:self action:@selector(recordStart) forControlEvents:UIControlEventTouchDown];
        //        // Set record end action for UIControlEventTouchUpInside
        //        [_tapeBt addTarget:self action:@selector(recordEnd) forControlEvents:UIControlEventTouchUpInside];
        //        // Set record cancel action for UIControlEventTouchUpOutside
        //        [_tapeBt addTarget:self action:@selector(recordCancel) forControlEvents:UIControlEventTouchUpOutside];
        self.voice = [[LCVoice alloc] init];
        if (self.view.frame.size.height < 500) {
            [_tapeBt setFrame:CGRectMake(125, 370, 70, 70)];
        }else{
            [_tapeBt setFrame:CGRectMake(125, 450, 70, 70)];
        }
        [_tapeBt setBackgroundColor:[UIColor clearColor]];
        [_headerImgView addSubview:_tapeBt];
        [_addImgBt setTag:8888];
    }
    
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionUp) {
        [_tapeBt removeFromSuperview];
        [_imageview removeFromSuperview];
        [self recordCancel];
    }
}



-(void)closeDeatilView {
    
    [_deatilView removeFromSuperview];
}


-(void)openMenu {
    //在这里呼出下方菜单按钮项
    _myActionSheet = [[UIActionSheet alloc]initWithTitle:nil
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];

    [_myActionSheet showInView:self.view];
  
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    //呼出的菜单按钮点击后的响应
    if (buttonIndex == _myActionSheet.cancelButtonIndex)
    {
        [_addImgBt setTag:8888];
    }
    switch (buttonIndex)
    {
    case 0:  //打开照相机拍照
        [self takePhoto];
        break;
    case 1:  //打开本地相册
        [self LocalPhoto];
        break;
    }
}


-(void)takePhoto {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentModalViewController:picker animated:YES];
    }else{
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
//打开本地相册
-(void)LocalPhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑    picker.allowsEditing = YES;
    [self presentModalViewController:picker animated:YES];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentTime = [formatter stringFromDate:[NSDate date]];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        //关闭相册界面
        [picker dismissModalViewControllerAnimated:YES];
        
        //在视图中显示选择的图片
        
        _headerImgView.image = image;
        //加在视图中
//        [self.view addSubview:smallimage];
        _boole = NO;
    }
    [_addImgBt removeFromSuperview];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"您取消了选择图片");
    [picker dismissModalViewControllerAnimated:YES];
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_timeArray.count != 0) {
        return _timeArray.count;
    }
    return 0;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
   
    
    // Request table view to reload
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
     NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(),[_timeArray objectAtIndex:indexPath.row]];
    // Remove the row from data model
    
    [_timeArray removeObjectAtIndex:indexPath.row];
    [_voiceList beginUpdates];
    [_voiceList deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [_voiceList endUpdates];
    
        BOOL bRet = [fileMgr fileExistsAtPath:filePath];
    if (bRet) {
        //
        NSError *err;
        [fileMgr removeItemAtPath:filePath error:&err];
        if (_imagesArray.count > indexPath.row || [_imagesArray objectAtIndex:indexPath.row] != nil) {
            NSString *filePathOne = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(),[_imagesArray objectAtIndex:indexPath.row]];
            [_imagesArray removeObjectAtIndex:indexPath.row];
            [fileMgr removeItemAtPath:filePathOne error:&err];
        }
    }
}

- (BOOL)isFileExitsAtPath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) {
        return YES;
    }
    
    return NO;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    _ListCell = [tableView dequeueReusableCellWithIdentifier:@"ListCell"];
    if (_ListCell == nil) {
        _ListCell = [[TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    _ListCell.selectionStyle = UITableViewCellSelectionStyleNone;

  //  _ListCell.selectionStyle = UITable ViewCellSelectionStyleNone;
    if (_timeArray.count != 0) {
    _ListCell.titleLabel.text = [_timeArray objectAtIndex:indexPath.row];
        if (_imagesArray.count > indexPath.row) {
            NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(),[_imagesArray objectAtIndex:indexPath.row]];
            NSData *imageData = [NSData dataWithContentsOfFile:filePath];
            _ListCell.iamge.image = [UIImage imageWithData:imageData scale:1.0];
            _ListCell.voiceTime.tag = indexPath.row;
            [_ListCell.voiceTime addTarget:self action:@selector(playVoice:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            _ListCell.iamge.image = [UIImage imageNamed:@"head"];        }

    }
    return _ListCell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //初始化音乐
    //创建音乐文件路径
  //  NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:[_fileArray objectAtIndex:indexPath.row] ofType:@"caf"];
    
  
//    CATransition *trans = [CATransition animation];
//    [trans setType:kCATransitionReveal];
//    [trans setDuration:0.7];
//    [trans setSubtype:kCATransitionFromBottom];
//    CALayer *layer = _deatilView.layer;
//    [layer addAnimation:trans forKey:@"Transition"];
    
    NSString *Path = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(),[_imagesArray objectAtIndex:indexPath.row]];
    NSData *imageData = [NSData dataWithContentsOfFile:Path];
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.image = [UIImage imageNamed:@"图片放大"];
    UIImageView *image = [[UIImageView alloc] init];
    
    UIButton *closeBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [closeBt setBackgroundColor:[UIColor clearColor]];
    [closeBt addTarget:self action:@selector(closeDeatilView) forControlEvents:UIControlEventTouchUpInside];
    [imgView addSubview:closeBt];
    
    
    if (self.view.frame.size.height < 500) {
        [image setFrame:CGRectMake(0 , 0, 320, 480)];
        [imgView setFrame:CGRectMake(0, 20, 320, 480)];
        [closeBt setFrame:CGRectMake(270, 405, 40, 30)];
    }else{
        [image setFrame:CGRectMake(0, 0, 320, 568)];
        [imgView setFrame:CGRectMake(0, 20, 320, 568)];
        [closeBt setFrame:CGRectMake(270, 480, 40, 30)];
    }
    
    
    _deatilView.userInteractionEnabled = YES;
    imgView.userInteractionEnabled = YES;

    image.image = [UIImage imageWithData:imageData scale:1.0];
    image.backgroundColor = [UIColor whiteColor];
    [_deatilView addSubview:image];
    
    [_deatilView addSubview:imgView];
    [self.view addSubview:_deatilView];
    
   
}

-(void)playVoice:(id)sender {
    if (_myBackMusic != nil) {
        _myBackMusic = nil;
    }
    UIButton *button = (UIButton *)sender;
    NSLog(@"%@",button.titleLabel.text);
      NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(),[_timeArray objectAtIndex:button.tag]];
    //判断文件是否存在·
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSURL *musicURL = [NSURL fileURLWithPath:filePath];
        
        NSError *myError = nil;
        //创建播放器
        _myBackMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:&myError];
        if (_myBackMusic == nil)
        {
            NSLog(@"error === %@",[myError description]);
        }
    //    _myBackMusic.numberOfLoops = -1;//设置音乐播放次数  -1为一直循环
        [_myBackMusic play];
        NSLog(@"%f",_myBackMusic.duration);
        
    }
    [button setTitle:[NSString stringWithFormat:@"%i S",(int)_myBackMusic.duration] forState:UIControlStateNormal];
}

-(void)changeLabelText {
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 86;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)Click:(UIButton *)sender{
    
    if (_addImgBt.tag == 9999) {
        //执行程序
        _navView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 64)];
        _navView.image = [UIImage imageNamed:@"didi_01"];
        _navView.userInteractionEnabled = YES;
        UIButton *backBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        UIButton *changeImage = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        
        [backBt setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
       // [backBt setTitle:@"hehe" forState:UIControlStateNormal];
        [changeImage setBackgroundImage:[UIImage imageNamed:@"change"] forState:UIControlStateNormal];
        
        [backBt addTarget:self action:@selector(recordCancel) forControlEvents:UIControlEventTouchUpInside];
        [changeImage addTarget:self action:@selector(openMenu) forControlEvents:UIControlEventTouchUpInside];
        
        [backBt setFrame:CGRectMake(0, 21, 50, 44)];
        [changeImage setFrame:CGRectMake(240, 21, 80, 44)];
        [_navView addSubview:backBt];
        [_navView addSubview:changeImage];
        
        _imageview = [[UIImageView alloc] init];
        _imageview.image = [UIImage imageNamed:@"di_02"];
        _headerImgView.image = [UIImage imageNamed:@""];
        [self.view addSubview:_imageview];
        _headerImgView.backgroundColor = [UIColor whiteColor];
        [_addImgBt setBackgroundImage:[UIImage imageNamed:@"photo"] forState:UIControlStateNormal];
        _tapeBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_tapeBt setBackgroundImage:[UIImage imageNamed:@"mike_05"] forState:UIControlStateNormal];
        // Set record start action for UIControlEventTouchDown
        [_tapeBt addTarget:self action:@selector(recordStart) forControlEvents:UIControlEventTouchDown];
//        // Set record end action for UIControlEventTouchUpInside
//        [_tapeBt addTarget:self action:@selector(recordEnd) forControlEvents:UIControlEventTouchUpInside];
//        // Set record cancel action for UIControlEventTouchUpOutside
//        [_tapeBt addTarget:self action:@selector(recordCancel) forControlEvents:UIControlEventTouchUpOutside];
        self.voice = [[LCVoice alloc] init];

        if (self.view.frame.size.height < 500) {
            [_tapeBt setFrame:CGRectMake(125, 362, 70, 70)];
            [_headerImgView setFrame:CGRectMake(0, 0, 320, 480)];
            [_addImgBt setFrame:CGRectMake(105, 160, 100, 111)];
            [_imageview setFrame:CGRectMake(0, 397.5, 320, 82.5)];
        }else{
            [_tapeBt setFrame:CGRectMake(125, 450, 70, 70)];
            [_headerImgView setFrame:CGRectMake(0, 0, 320, 568)];
            [_addImgBt setFrame:CGRectMake(105, 230, 100, 111)];
            [_imageview setFrame:CGRectMake(0, 485.5, 320, 82.5)];
        }
        [self.view insertSubview:_navView atIndex:100];
        [_tapeBt setBackgroundColor:[UIColor clearColor]];
        [_headerImgView addSubview:_tapeBt];
        [_addImgBt setTag:8888];
    }else{
        
        [self openMenu];
        [_addImgBt setTag:9999];}

}

//开始录音
-(void) recordStart
{
    [_tapeBt removeFromSuperview];
    [_addImgBt removeFromSuperview];
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    _currentTime = [formatter stringFromDate:[NSDate date]];
    _deleteFileUrl = [NSString stringWithFormat:@"%@/Documents/%@.caf", NSHomeDirectory(),_currentTime];
    [self.voice startRecordWithPath:_deleteFileUrl];
    _filePath = [NSString stringWithFormat:@"%@/Documents/%@.png", NSHomeDirectory(),_currentTime];
    
    _endBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _cancelBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    if (self.view.frame.size.height < 500) {
        [_endBt setFrame:CGRectMake(30, 419, 73.5, 41.5)];
        [_cancelBt setFrame:CGRectMake(220, 419, 73.5, 41.5)];
    }else{
    [_endBt setFrame:CGRectMake(30, 499, 73.5, 41.5)];
    [_cancelBt setFrame:CGRectMake(220, 499, 73.5, 41.5)];
    }
    if (_boole == YES) {
        _headerImgView.image = [UIImage imageNamed:@"penta"];
        _boole = NO;
    }
    
    
//    [_endBt setTitle:@"保存" forState:UIControlStateNormal];
//    [_cancelBt setTitle:@"取消" forState:UIControlStateNormal];
    
    UIGraphicsBeginImageContext(_headerImgView.bounds.size);
    [_headerImgView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIGraphicsEndImageContext();
    
    BOOL result = [UIImagePNGRepresentation(_headerImgView.image)writeToFile: _filePath atomically:YES];
    
    [_endBt setBackgroundImage:[UIImage imageNamed:@"qxbc_05"] forState:UIControlStateNormal];
    [_cancelBt setBackgroundImage:[UIImage imageNamed:@"qxbc_03"] forState:UIControlStateNormal];
    [_endBt addTarget:self action:@selector(recordEnd) forControlEvents:UIControlEventTouchUpInside];
    [_cancelBt addTarget:self action:@selector(recordCancel) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_endBt atIndex:10000];
    [self.view insertSubview:_cancelBt atIndex:10000];
}

//完成录音,将音频存入本地沙盒
-(void) recordEnd
{
    [self.voice stopRecordWithCompletionBlock:^{
        
        if (self.voice.recordTime > 0.0f) {
           
        }
    }];
    
       UIGraphicsBeginImageContext(_headerImgView.bounds.size);
    [_headerImgView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIGraphicsEndImageContext();
    
    BOOL result = [UIImagePNGRepresentation(_headerImgView.image)writeToFile: _filePath atomically:YES]; // 保存成功会返回YES
    [self addViewsAndKits];
    [_endBt removeFromSuperview];
    [_cancelBt removeFromSuperview];
    [_voiceList reloadData];
    [self.voice cancelled];
}

//取消录音
-(void) recordCancel
{
    [self.voice cancelled];
    [_navView removeFromSuperview];
    [_tapeBt removeFromSuperview];
    [_imageview removeFromSuperview];
    [_addImgBt setFrame:CGRectMake(245, 43, 45, 45)];
    [_addImgBt setBackgroundImage:[UIImage imageNamed:@"jia_03"] forState:UIControlStateNormal];
    [_addImgBt setTag:9999];
//    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"取消了" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
//    [alert show];
    if (_addImgBt.superview == nil) {
        [self.view addSubview:_addImgBt];
    }
    [_endBt removeFromSuperview];
    [_cancelBt removeFromSuperview];
    [_headerImgView setFrame:CGRectMake(0, 0, 320,182)];
    _headerImgView.image = [UIImage imageNamed:@"di_01"];
    _boole = YES;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
    // Remove the row from data model
    
  //  [_timeArray removeObjectAtIndex:indexPath.row];
    [_voiceList beginUpdates];
   // [_voiceList deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [_voiceList endUpdates];
    
    BOOL bRet = [fileMgr fileExistsAtPath:_deleteFileUrl];
    if (bRet) {
        //
        NSError *err;
        [fileMgr removeItemAtPath:_deleteFileUrl error:&err];
        [fileMgr removeItemAtPath:_filePath error:&err];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sende  r:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
